import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import Login from '@/views/Login.vue'
import Layout from '@/views/Layout.vue'
import Dashboard from '@/views/Dashboard.vue'
import User from '@/views/User.vue'
import Role from '@/views/Role.vue'
import Permission from '@/views/Permission.vue'
import Profile from '@/views/Profile.vue'
import NoPermission from '@/views/NoPermission.vue'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: { requiresAuth: false }
  },
  {
    path: '/no-permission',
    name: 'NoPermission',
    component: NoPermission,
    meta: { requiresAuth: true }
  },
  {
    path: '/',
    component: Layout,
    meta: { requiresAuth: true },
    children: [
      {
        path: '',
        name: 'Dashboard',
        component: Dashboard,
        meta: { title: '首页' }
      },
      {
        path: 'user',
        name: 'User',
        component: User,
        meta: { title: '用户管理', permission: 'system:user:query' }
      },
      {
        path: 'role',
        name: 'Role',
        component: Role,
        meta: { title: '角色管理', permission: 'system:role:query' }
      },
      {
        path: 'permission',
        name: 'Permission',
        component: Permission,
        meta: { title: '权限管理', permission: 'system:permission:query' }
      },
      {
        path: 'profile',
        name: 'Profile',
        component: Profile,
        meta: { title: '个人信息' }
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  const authStore = useAuthStore()
  
  // 如果路由需要认证
  if (to.meta.requiresAuth !== false) {
    // 检查是否已登录
    if (!authStore.isLoggedIn) {
      // 如果当前不在登录页，则跳转到登录页
      if (to.path !== '/login') {
        next('/login')
        return
      }
    } else {
      // 如果已登录，检查权限数据是否有效
      if (!authStore.validatePermissionState()) {
        // 权限状态无效，尝试刷新
        try {
          await authStore.refreshUserData()
          
          // 再次验证权限状态
          if (!authStore.validatePermissionState()) {
            // 如果仍然无效，清除状态并跳转登录页
            authStore.logout()
            next('/login')
            return
          }
        } catch (error) {
          console.error('刷新权限失败:', error)
          // 如果刷新失败，跳转到登录页
          authStore.logout()
          next('/login')
          return
        }
      }
    }
    
    // 检查权限
    if (to.meta.permission) {
      if (!authStore.hasPermission(to.meta.permission)) {
        next('/no-permission')
        return
      }
    }
  }
  
  // 如果已登录且访问登录页，重定向到首页
  if (to.path === '/login' && authStore.isLoggedIn) {
    next('/')
    return
  }
  
  next()
})

export default router 